<?php

require_once 'PipesImpl/Config.php';
require_once 'PipesImpl/Route.php';

class Pipes_Route implements PipesImpl_Route
{
	private $_data   = array();

	public function __construct(PipesImpl_Config $config, $route) 
	{
		$route = str_replace($config->base_uri, '', $route);
		if (isset($config->page_type)) {
			$this->_data['page_type'] = $config->page_type;
		}

		preg_match('/\/?([a-z0-9_-]+)(\/(([a-z0-9_\.-]+)\/?)?(.*))?/i', $route, $matches);
		
		$this->_data['controller'] = $matches[1];
		if (!empty($matches[4])) {
			$this->_data['action'] = $matches[4];
			$startOfPageType = strpos($this->_data['action'], '.');
			//var_dump($this->_data['action']);
			if ($startOfPageType !== false) {
				$this->_data['page_type'] = substr($this->_data['action'], $startOfPageType + 1);
			}
		}

		if (!empty($matches[5])) {
			$extras = explode('?', $matches[5]);
			$this->_data['extras'] = explode('/', array_shift($extras));
			if (empty($this->_data['extras'][0])) {
				$this->_data['extras'] = array();
			}
			parse_str(array_shift($extras), $queryString);
			$this->_data['extras'] = array_merge($this->_data['extras'], $queryString);
		}
	}

	public function __get($key) {
		$return = null;
		switch($key) {
			case 'controller' :
			case 'action' :
			case 'extras' :
			case 'page_type' :
				$return = $this->_data[$key];
				break;
		}

		return $return;
	}

	public function __isset($key) 
	{
		return isset($this->_data[$key]);
	}
}
